<?php

namespace app\shop\controller;

use think\Controller;
use app\common\library\Email;
use app\common\controller\Shop;


// Vue商城控制器
class Business extends Controller
{
    public function __construct()
    {
    parent::__construct();

    $this->BusinessModel = model('Business.Business');
    $this->SourceModel = model('Business.Source');
    $this->CouponModel = model('Coupon.Coupon');
    $this->ReceiveModel = model('Coupon.Receive');

    }

    // 注册
    public function register()
    {
            // echo 1111222;
            if($this->request->isAjax())
            {
                $mobile = $this->request->param('mobile', '', 'trim');
                $password = $this->request->param('password', '', 'trim');

            //先获取客户来源
            $sourceid = $this->SourceModel->where(['name'=>['LIKE', "%家居商城%"]])->value('id');
            
            
            //生成密码盐。randstr()方法，在之前封装的公共控制器common.php
            $salt = randstr();

            //密码进行加密
            $password = md5($password.$salt);

            //组装数据
            $data = [
                'mobile' => $mobile,
                'nickname' => build_encrypt($mobile, 3, 4, '*'), //脱敏显示
                'password' => $password,
                'salt' => $salt,
                'gender' => '0',
                'sourceid' => $sourceid,
                'deal' => '0',
                'money' => '0',
                'auth' => '0'
            ];

            //执行插入语句,插入成功会自动返回影响函数
            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if($result === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }else
            {
                // 注册成功，就跳转到'/business/login'
                $this->success('注册成功', '/business/login');
                exit;
            }
            }
    }



    // 登录
    public function login()
    {
        if($this->request->isAjax())
        {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            //根据手机号码查询用户是否存在
            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if(!$business)
            {
                $this->error('该手机号用户不存在');
                exit;
            }

            if(empty($password))
            {
                $this->error('密码不能为空');
                exit;
            }

            //验证密码
            $salt = $business['salt'];
            $repass = md5(md5($password.$salt));

            //如果加密的密码和数据库的密码要是不一致就说明密码错误
            if($repass != $business['password'])
            {
                $this->error('密码错误');
                exit;
            }

            // 删除密码和密码盐
            unset($business['salt']);
            // unset($business['password']);
            
            $this->success('登录成功','/business/index', $business);
            exit;
        }
    }


    // 检查是否有登录
    public function check()
    {
        if($this->request->isAjax())
        {
            // 在main.js的钩子函数，登陆时传过来
            $id = $this->request->param('id', 0, 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            if(!$id || empty($mobile))
            {
                $this->error('请重新登录', '/business/login');
                exit;
            }

            //根据id和手机号 找出具体人
            $where = ['id'=>$id, 'mobile'=>$mobile];
            $business = $this->BusinessModel->where($where)->find();

            if(!$business)
            {
                $this->error('非法登录', '/business/login');
                exit;
            }

            unset($business['salt']);
            unset($business['password']);

            $this->success('用户存在', null, $business);
            exit;
        }
    }

    // 个人资料
    public function profile()
    {

        if($this->request->isAjax())
        {
            $id = $this->request->param('id', 0, 'trim');
            $nickname = $this->request->param('nickname', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $gender = $this->request->param('gender', '0', 'trim');
            $code = $this->request->param('code', '', 'trim');

            var_dump($code);
            // die;
            
            $business = $this->BusinessModel->find($id);

            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            
            //组装数据
            $data = [
                'id' => $id,
                'nickname' => $nickname,
                'mobile' => $mobile,
                'email' => $email,
                'gender' => $gender,
            ];

            //判断密码
            if(!empty($password))
            {
                //重新生成密码盐
                $salt = build_ranstr(10);
                $repass = md5($password.$salt);
                $data['salt'] = $salt;
                $data['password'] = $repass;
            }

            //邮箱 判断认证状态
            if($business['email'] != $email)
            {
                $data['auth'] = '0';
            } 

            //判断地区
            if(!empty($code))
            {
                $parent = model('Region')->where(['code' => $code])->value('parentpath');

                //将字符串转换为数组
                $list = explode(',', $parent);

                $data['province'] = isset($list[0]) ? $list[0] : null;
                $data['city'] = isset($list[1]) ? $list[1] : null;  
                $data['district'] = isset($isset[2]) ? $list[2] : null;
            }

            //判断是否有上传图片
            if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0)
            {
                $success = build_upload('avatar');
                if($success['code'])
                {
                    $data['avatar'] = $success['data'];
                }else
                {
                    $this->error($success['msg']);
                    exit;
                }
            }

            //更新
            // 验证器里面也有个点拼接起来表示验证场景
            $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            //更新成功，判断是否有旧图片 如果有就删除
            if(isset($data['avatar']))
            {
                //判断他是否是一个图片，如果是就删除
                @is_file(".".$business['avatar']) && @unlink(".".$business['avatar']);
            }
            
            $this->success('更新成功', '/business/index');
            exit;
        }
    }


    //添加收货地址
    public function add()
    {
        if($this->request->isPost())
        {
            // 拿状态
            $params = $this->request->param();

            $code = $this->request->param('code', '', 'trim');
            $status = $this->request->param('status', '0', 'trim');

            //判断是否有地区数据
            if(!empty($code))
            {
                //查询省市区的地区码出来
                $parent = model('Region')->where(['code' => $code])->value('parentpath');
                
                if(!empty($parent))
                {
                    $arr = explode(',', $parent);
                    $params['province'] = isset($arr[0]) ? $arr[0] : null;
                    $params['city'] = isset($arr[1]) ? $arr[1] : null;
                    $params['district'] = isset($arr[2]) ? $arr[2] : null;
                }
            }

            //开启事务
            $this->AddressModel->startTrans();

            //判断是否选择了默认收货地址
            if($status == '1')
            {
                //直接去更新覆盖，将已有的数据变成0
                $AddressStatus = $this->AddressModel->where(['busid'=>$this->business['id']])->update(['status' => '0']);

                if($AddressStatus === FALSE)
                {
                    $this->error('更新默认地址状态有误');
                    exit;
                }
            }

            //插入数据
            $result = $this->AddressModel->validate('common/Business/Address')->save($params);

            if($result === FALSE)
            {
                $this->AddressModel->rollback();
                $this->error($this->AddressModel->getError());
                exit;
            }else
            {
                $this->AddressModel->commit();
                $this->success('添加成功');
                exit;
            }
        }
    }




    //获取优惠券
    public function coupon()
    {
        $busid = $this->request->param('busid', 0, 'trim');

        $business = $this->BusinessModel->find($busid);

        if(!$business)
        {
            $this->error('用户不存在');
            exit;
        }

        //要找出当前这个人所领取的优惠券
        $coupon = $this->ReceiveModel->with(['coupon'])->where(['busid' => $busid, 'receive.status' => '1'])->select();
        
        if($coupon)
        {
            $this->success('返回优惠券', null, $coupon);
            exit;
        }else
        {
            $this->error('无优惠券信息');
            exit;
        }


    }




}




  





